package util;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

import java.io.InputStream;
import java.util.Properties;

public class MorphiaUtil {
    private static final Properties prop = new Properties();
    private static final MongoClient client ;
    static{
        InputStream in = null;
        try {
            in=MorphiaUtil.class.getResourceAsStream("/mongo.properties");
            prop.load(in);
            //在连接池中获得一个client
            //创建一个mongo客户端参数拼接器
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //设置客户端的最大连接数
            builder.connectionsPerHost(Integer.parseInt(prop.getProperty("connectionsPerHost")));
            //设置如果连接被全部占用，新线程需要的等待最长时间
            builder.maxWaitTime(Integer.parseInt(prop.getProperty("maxWaitTime")));
            //设置每个连接连接mongo服务器的最大延迟时间
            builder.connectTimeout(Integer.parseInt(prop.getProperty("connectTimeout")));
            //使用构造器获得一个mongo得客户端配置参数对象
            MongoClientOptions options = builder.build();
            client = new MongoClient(new ServerAddress(prop.getProperty("ip"), Integer.parseInt(prop.getProperty("port"))),options);
        } catch (Exception e) {
            throw new RuntimeException("初始化mongo客户端配置文件异常",e);
        }
    }
    //获取客户端 client
    public static MongoClient getClic(){
        return client;
    }
    //获取database
    public static Datastore getDB(){
        Datastore ds = new Morphia().createDatastore(client,prop.getProperty("database"));
        return ds;
    }
}
